package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.entity.Contact;
import com.util.DBHelp;
import com.util.RowMapper;

public class ContactDao {
	private DBHelp<Contact> db = new DBHelp<Contact>();
	
	private class ContactRowMapper implements RowMapper<Contact> {

		public Contact mapRow(ResultSet rs) throws SQLException {
			
			Contact c = new Contact();
			c.setId(rs.getString("id"));
			c.setName(rs.getString("name"));
			c.setEmail(rs.getString("email"));
			c.setHome(rs.getString("home"));
			c.setPhone(rs.getString("phone"));
			c.setTel(rs.getString("tel"));
			c.setAddress(rs.getString("address"));
			c.setAdstruct(rs.getString("adstruct"));
			c.setCompany(rs.getString("company"));
			c.setWeibo(rs.getString("weibo"));
			c.setProjectid(rs.getString("projectid"));
			c.setCreatetime(rs.getString("createtime"));
			return c;
		}
		
		
	}

	public List<Contact> findAllContact(String projectid) {
		StringBuilder sql=new StringBuilder();
		sql.append("SELECT tc.`id`,tc.`address`,tc.`adstruct`,tc.`company`,tc.`email`,");
		sql.append("tc.`home`,tc.`name`,tc.`phone`,tc.`projectid`,tc.`tel`,tc.`weibo`,tc.`createtime`  ");
		sql.append("FROM t_contact AS tc ");
		sql.append(" where tc.`projectid`=?  ORDER BY tc.`createtime` DESC ");
		return db.executeQueryForList(sql.toString(), new ContactRowMapper(),projectid);
	}

	public void save(Contact c) {
		String sql="INSERT INTO t_contact(id,projectid,`name`,address,adstruct,company,email,`home`,phone,tel,weibo,createtime) values(?,?,?,?,?,?,?,?,?,?,?,?)";
		db.executeSQL(sql, c.getId(),c.getProjectid(),c.getName(),c.getAddress(),c.getAdstruct(),c.getCompany(),c.getEmail(),c.getHome(),c.getPhone(),c.getTel(),c.getWeibo(),c.getCreatetime());
	}

	public Contact findContactById(String id) {
		StringBuilder sql=new StringBuilder();
		sql.append(" SELECT id,address,adstruct,company,email,");
		sql.append("home,name,phone,projectid,tel,weibo,createtime ");
		sql.append("FROM t_contact where id=?  ORDER BY createtime DESC ");
		return db.executeQueryForObject(sql.toString(), new ContactRowMapper(),id);
	}

	public void update(Contact c) {
		StringBuilder sql=new StringBuilder();
		sql.append("UPDATE  t_contact SET `name` = ? ,address =  ?, ");
		sql.append("adstruct = ?,company = ?,email= ?,home= ?,phone= ?, tel= ?,weibo= ? WHERE id=? ");

		db.executeSQL(sql.toString(),c.getName(),c.getAddress(),c.getAdstruct(),c.getCompany(),c.getEmail(),c.getHome(),c.getPhone(),c.getTel(),c.getWeibo(),c.getId());
	}

	public void delById(String id) {
		StringBuilder sql=new StringBuilder();
		sql.append("delete from t_contact where id=? ");
		db.executeSQL(sql.toString(),new ContactRowMapper());
	}

	
}
